<template>
	<view class="bg-white padding-top">
		<view class="grid col-3 grid-square flex-sub">
			<view></view>
			<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
				:data-url="imgList[index]">
				<image :src="imgList[index]" mode="aspectFill"></image>
				<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
					<text class='cuIcon-close'></text>
				</view>
			</view>
			<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
				<text class='cuIcon-cameraadd'></text>
			</view>
		</view>
		<view class="text-sm text-red text-center">说明：拍照算数题，自动检查</view>
		<view class="text-sm text-red text-center margin-top" v-if="errMsg">{{errMsg}}</view>
		
		<view class="padding flex justify-between">
			<button style="width: 50%;" class="cu-btn bg-orange round lg" @click="submit">开始检查</button>
			<button style="width: 50%;" class="cu-btn bg-green margin-left round lg" @click="reset">清空</button>
		</view>
		<view class="bg-white" style="position: relative;min-height: 60vh;">
			<image :src="imgList[0]" class="image" mode="widthFix"></image>
			<!-- 试卷模式 -->
			<!-- <view class="item" :style="[{'left': (v.words.words_location.left / sections.x * 100) + '%'}, {'top': (v.words.words_location.top / sections.y * 100) + '%'}]" v-for="v in list" >
				<view class="text-bold" v-if="v.words.word.includes('=')">
					<view v-if="v.check" class="cuIcon-check text-green"></view>
					<view v-else class="cuIcon-close text-red"></view>
				</view>
				<view class="text-red text-bold">{{v.words.word}}</view>
			</view> -->
			<!-- 通用模式 -->
			
			<view class="item"
				:style="[{'left': (Number(v.form_location.left) / Number(sections.x) * 100) + '%'}, {'top': (Number(v.form_location.top) / Number(sections.y) * 100) + '%'}]"
				v-for="v in list">
				<view class="text-bold" v-if="v.form_words.includes('=')">
					<view v-if="v.check" class="cuIcon-check text-green"></view>
					<view v-else class="cuIcon-close text-red">
						{{v.form_words}}
					</view>
				</view>
				<!-- <view class="text-red text-bold">{{v.form_words}}</view> -->
			</view>
		</view>

	</view>

</template>

<script>
	// import Tesseract from 'tesseract.js'
	// import {
	// 	createWorker
	import {
		evalMath
	} from "../../js_sdk/hzbgg-evalMath/eval-math/eval-math.js"
	import baiduApi from '../../api/baiduApi';
	import config from '../../config';
	// } from 'tesseract.js'
	export default {
		data() {
			return {
				title: 'Hello',
				imgList: [],
				columnNum: 0,
				lineList: [1],
				errMsg: "",
				list: [],
				sections: {},
				wechatToken: ""
			}
		},
		onShareAppMessage: function(res) {
			return {
				title: '算数检查',
				path: '/pages/index/index',
				imageUrl: require("../../static/logo.jpg") // 分享卡片的图片，可选
			}
		},
		onLoad() {
			this.getToken()
			// this.getWechatToken()
		},
		methods: {
			// getWechatToken() {
			// 	baiduApi.getWechatAccessToken({
			// 		grant_type: "client_credential",
			// 		appid: "wxcf58bc897dc68602",
			// 		secret: "2dc77d4d019e68ee8be3643302f7aba9"
			// 	}).then(res => {
			// 		this.wechatToken = res.access_token
			// 	})
			// },
			getToken() {
				// baiduApi.getToken().then(res => {

				// })
			},
			async ChooseImage() {
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: async (res) => {
						console.log("res", res)
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						this.submit()
						// const worker = await createWorker();
						// await worker.loadLanguage(
						// 'eng+chi_sim'); // eng(英文) / chi_sim(简体中文) / chi_tra(繁体中文) / eng+chi_sim(英文+简体中文) / (如果有多种语言用+连接即可)
						// await worker.initialize('eng+chi_sim'); //使用一种语言会快一些,多种语言混合会慢一些
						// console.log("识别")
						// try{
						// 	const res1 = await worker.recognize(res.tempFilePaths[0]);
						// 	console.log('识别结果:', res1); //text是最后识别到的内容
						// 	await worker.terminate(); //终止worker线程,节省内存资源
						// 	this.createLineList(res1.data.lines)
						// }catch(e){
						// 	console.log(e)
						// 	//TODO handle the exception
						// }

						// worker.recognize(res.tempFilePaths[0]).then(res1 => {
						// 	console.log("res1", res1)
						// })
					}
				});
			},
			submit() {
				if (!this.imgList[0]) {
					uni.showToast({
						icon: "none",
						title: "请先拍照"
					})
					return
				}
				
				baiduApi.getAccessToken().then(res => {
					console.log("Res", res)
					const accessToken = res
					// #ifdef H5
					this.recognize(accessToken, this.imgList[0])
					// #endif
					// #ifdef MP-WEIXIN
					this.recognizeWx(accessToken, this.imgList[0])
					// #endif
				})
			},
			recognizeWx(token, url) {
				this.getImageSections(url)
				uni.getFileSystemManager().readFile({
					filePath: url, //要读取的文件的路径 (本地路径)
					encoding: "base64", //指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
					success: (res) => {
						//转换完毕，执行上传
						baiduApi.ocr({
							token: token,
							recg_formula: true,
							image: res.data
						}).then(res => {
							if (res.error_code) {
								this.errMsg = res.error_msg
								return
							}
							this.getFormulaResult(res.formula_result)
							// this.getResult(res.results)
							// this.getResultNormal(res.words_result)
							this.list = res.formula_result
							console.log("this.list.any(item => item.form_words.includes('='))", this.list.some(item => item.form_words.includes('=')))
							if (!this.list.some(item => item.form_words.includes('='))) {
								uni.showToast({
									title: "内容不合法",
									icon: "none"
								})
								this.reset()
							}
						})
					}
				})
			},
			recognize(token, url) {
				this.getImageSections(url)
				uni.request({
					url: url,
					method: "GET",
					responseType: "arraybuffer",
					success: res => {
						let base64 = uni.arrayBufferToBase64(res.data)
						baiduApi.ocr({
							token: token,
							recg_formula: true,
							image: base64
						}).then(res => {
							this.getFormulaResult(res.formula_result)
							// this.getResult(res.results)
							// this.getResultNormal(res.words_result)
							this.list = res.formula_result
							console.log("this.list.any(item => item.form_words.includes('='))", this.list.any(item => item.form_words.includes('=')))
							if (!this.list.any(item => item.form_words.includes('='))) {
								uni.showToast({
									title: "内容不合法",
									icon: "none"
								})
								this.reset()
							}
						})
					},
					fail: (err) => {
						console.log("err", err)
					}
				})
			},
			selfEval(str) {
				console.log("evalMath(str)", evalMath(str))
				return evalMath(str);
			},
			getFormulaResult(list) {
				console.log("list1", list)
				list.map(item => {
					item.form_words = item.form_words.split(" ").join("")
					if (item.form_words.includes("=")) {
						const calcRes = this.selfEval(item.form_words.split("=")[0])
						console.log("calcRes", calcRes)
						if (calcRes == item.form_words.split("=")[1]) {
							item.check = true
						} else {
							item.check = false
							console.log("题目：", item.form_words)
							console.log('正确结果：', this.selfEval(item.form_words.split("=")[0]))
							console.log('识别结果：', item.form_words.split("=")[1])
						}
					}
				})
			},
			// 试卷模式
			getResult(list) {
				console.log("list1", list)
				const srcList = list.filter(item => (item.words.word.includes("=")))
				const tagList = list
				console.log("srcList", srcList)
				console.log("tagList", tagList)
				list.map((item, i) => {
					if (item.words.word.includes("=") && (item.words_type == "print")) {
						console.log("找到题目:" + i, item.words.word)
						const left = Number(item.words.words_location.left) + Number(item.words.words_location
							.width)
						const top = Number(item.words.words_location.top)
						console.log("left:", left)
						console.log("top", top)
						const index = tagList.findIndex(o => (Math.abs((Number(o.words.words_location.left) -
							left)) <= 10) && (Math.abs(Number(o.words.words_location.top) - top) <= 25))
						if (index != -1) {
							console.log("找到了结果", tagList[index].words.word)
							if (this.selfEval(item.words.word.split("=")[0]) == tagList[index].words.word) {
								item.check = true
							} else {
								item.check = false
							}
							console.log('this.selfEval(item.words.word.split("=")[0])', this.selfEval(item.words
								.word.split("=")[0]))
							console.log("判断结果:", item.check)
						}
					}
				})
				console.log("list", list)
			},
			// 正常模式
			getResultNormal(list) {
				console.log("list1", list)
				const srcList = list.filter(item => (item.words.includes("=")))
				const tagList = list
				console.log("srcList", srcList)
				console.log("tagList", tagList)
				list.map((item, i) => {
					if (item.words.includes("=")) {
						const left = Number(item.location.left) + Number(item.location.width)
						const top = Number(item.location.top)
						const index = tagList.findIndex(o => (Math.abs((Number(o.location.left) - left)) <= item
							.location.height) && (Math.abs(Number(o.location.top) - top) <= item.location
							.height))
						if (index != -1) {
							if (this.selfEval(item.words.split("=")[0]) == tagList[index].words) {
								item.check = true
							} else {
								item.check = false
								console.log("找到题目:" + i, item.words)
								console.log("left:", left)
								console.log("top", top)
								console.log("找到了结果", tagList[index].words)
								console.log('this.selfEval(item.words.split("=")[0])', this.selfEval(item.words
									.split("=")[0]))
								console.log("判断结果:", item.check)
							}
						}
					}
				})
				console.log("list", list)
			},
			getImageSections(url) {
				uni.getImageInfo({
					src: url,
					success: res => {
						console.log("res", res)
						this.sections = {
							x: res.width,
							y: res.height
						}
						console.log("sections", this.sections)
					}
				})
			},
			// createLineList(lineList) {
			// 	let maxColumnNum = 0
			// 	let tagList = []
			// 	lineList.map(item => {
			// 		const rowList = item.text.split(" ")
			// 		maxColumnNum = Math.max(rowList.length, maxColumnNum)
			// 		rowList.map(o => {
			// 			console.log("o", o)
			// 			console.log('o.split("=")[0]', o.split("=")[0])
			// 			if (eval(o.split("=")[0])) {
			// 				console.log('eval(o.split("=")[0])', eval(o.split("=")[0]))
			// 				tagList.push({
			// 					text: o + " " + eval(o.split("=")[0]),
			// 					result: (eval(o.split("=")[0]) == o.split("=")[1])
			// 				})
			// 			}
			// 		})
			// 	})
			// 	console.log("maxColumnNum", maxColumnNum)
			// 	this.lineList = tagList
			// 	this.columnNum = maxColumnNum
			// 	console.log("this.lineList", this.lineList)
			// },
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '召唤师',
					content: '确定要删除这段回忆吗？',
					cancelText: '再看看',
					confirmText: '再见',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
							this.list = []
						}
					}
				})
			},
			reset() {
				this.imgList = []
				this.list = []
			}
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.item {
		position: absolute;
	}

	.image {
		position: relative;
		width: 100%;
		height: 100%;
	}
</style>